﻿using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Borg.Framework
{
    public class SelectCommand : ICommand
    {
        private readonly string[][] _arguments =
            new[] { new string[0], new string[0] };

        public IEnumerable<string> GetArguments(string[] command, int pos)
        {
            switch (pos)
            {
                case 0:
                    return
                        (from si in Runtime.Repository.SlotInfos
                         where si.PluggedPlugInfos.Count > 0
                         select si.ToString()).ToArray();
                case 1:
                    int num;

                    if (ParseId(command[1], out num))
                    {
                        var si = Runtime.Repository.SlotInfos.Find(num);

                        return
                            (from pi in si.PluggedPlugInfos
                             where !si.SelectedPlugs.Contains(pi)
                             select pi.ToString()).ToArray();
                    }

                    return new string[0];
            }

            return null;
        }

        private static bool ParseId(string argument, out int id)
        {
            var flag = int.TryParse(argument, out id);

            if (!flag)
            {
                var regex = new Regex(".*{([0-9]*)");
                flag = int.TryParse(regex.Match(argument).Groups[1].Value, out id);
            }

            return flag;
        }

        private static string Select(string[] command)
        {
            int slot;
            int plug;

            if (command.Length < 3)
                return "Too few arguments.";

            if (!ParseId(command[1], out slot))
                return "Invalid slot";

            if (!ParseId(command[2], out plug))
                return "Invalid plug";

            var si = Runtime.Repository.SlotInfos.Find(slot);
            var pi = Runtime.Repository.PlugInfos.Find(plug);

            si.SelectPlugs(new[] { pi });
            return string.Empty;
        }

        public CommandHandler Handler
        {
            get { return Select; }
        }

        public string Help
        {
            get { return "  Help for command \"select\""; }
        }

        public string Name
        {
            get { return "select"; }
        }
    }
}

